package com.freightoa.foundation.net

import com.freightoa.foundation.net.api.AuthenticationInterceptor
import com.freightoa.foundation.net.api.UserAgentInterceptor
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

/**
 * 作者：lhgray on 2025/3/22.
 * 邮箱：lhgray@163.com
 * 文件：com.freightoa.base_foundation.net
 */
@Module
@InstallIn(SingletonComponent::class)
class DINetworkModule() {

    /**
     * 增加链接参数的方法 公共参数的
     */
    fun getAuthenticationInterceptor() = AuthenticationInterceptor()

    /**
     * 报文头拼装的方法
     */
    fun getUserAgentInterceptor() = UserAgentInterceptor()

    fun getApiResultAdapterFactory() = ApiResultAdapterFactory()

    /**
     * 日志连接器的方法
     */

    // 创建一个自定义的 Logger 实现，使用 Timber 输出日志
    class TimberHttpLogger : HttpLoggingInterceptor.Logger {
        override fun log(message: String) {
            Timber.d(message)
        }
    }
    private fun getHttpLoggingInterceptor() = apply {

    }


/**
 * [OkHttpClient]依赖提供方法
 *
 * @return OkHttpClient
 */
@Singleton
@Provides
fun provideOkHttpClient(): OkHttpClient {
    val httpLoggingInterceptor = HttpLoggingInterceptor(TimberHttpLogger())
    httpLoggingInterceptor.level  = HttpLoggingInterceptor.Level.BODY
    return OkHttpClient.Builder()
        .connectTimeout(15L * 1000L, TimeUnit.MILLISECONDS)
        .readTimeout(20L * 1000L, TimeUnit.MILLISECONDS)
        .addInterceptor(AuthenticationInterceptor())
        .addInterceptor(httpLoggingInterceptor)
        .addInterceptor(HeaderInterceptor())
        .retryOnConnectionFailure(true)
        .build()
}

/**
 * 项目主要服务器地址的[Retrofit]依赖提供方法
 *
 * @param okHttpClient OkHttpClient OkHttp客户端
 * @return Retrofit
 */
@Provides
@Singleton
fun provideMainRetrofit(okHttpClient: OkHttpClient): Retrofit {
    return Retrofit.Builder()
        .baseUrl("https://app3.freightoa.com")
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(ApiResultAdapterFactory())
        .client(okHttpClient)
        .build()
}
}